<template>
  <div class="admin-inventory-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>管理员库存管理</span>
          <div>
            <el-button type="primary" @click="handleRefresh">刷新</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="商品名称">
            <el-input
              v-model="searchForm.productName"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="商品编号">
            <el-input
              v-model="searchForm.productCode"
              placeholder="请输入商品编号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="操作类型">
            <el-select
              v-model="searchForm.recordType"
              placeholder="请选择操作类型"
              clearable
            >
              <el-option label="入库" value="IN" />
              <el-option label="出库" value="OUT" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务类型">
            <el-select
              v-model="searchForm.businessType"
              placeholder="请选择业务类型"
              clearable
            >
              <el-option label="新增商品" value="CREATE" />
              <el-option label="分配给商家" value="ALLOCATE" />
              <el-option label="库存调整" value="ADJUST" />
            </el-select>
          </el-form-item>
          <el-form-item label="操作员">
            <el-input
              v-model="searchForm.operatorName"
              placeholder="请输入操作员姓名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="目标商家">
            <el-input
              v-model="searchForm.targetMerchantName"
              placeholder="请输入商家名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="操作时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="recordNo" label="记录编号" width="180" />
        <el-table-column prop="productName" label="商品名称" min-width="120" />
        <el-table-column prop="productCode" label="商品编号" width="120" />
        <el-table-column prop="recordTypeName" label="操作类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.recordType === 'IN' ? 'success' : 'warning'">
              {{ scope.row.recordTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessTypeName" label="业务类型" width="120">
          <template #default="scope">
            <el-tag 
              :type="getBusinessTypeTagType(scope.row.businessType)"
              effect="plain"
            >
              {{ scope.row.businessTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="操作数量" width="100" />
        <el-table-column prop="beforeStock" label="操作前库存" width="120" />
        <el-table-column prop="afterStock" label="操作后库存" width="120" />
        <el-table-column prop="unitCost" label="单位成本" width="100">
          <template #default="scope">
            <span v-if="scope.row.unitCost">¥{{ scope.row.unitCost }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalCost" label="总成本" width="120">
          <template #default="scope">
            <span v-if="scope.row.totalCost">¥{{ scope.row.totalCost }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="操作员" width="100" />
        <el-table-column prop="targetMerchantName" label="目标商家" width="120">
          <template #default="scope">
            <span v-if="scope.row.targetMerchantName">{{ scope.row.targetMerchantName }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="操作时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="库存记录详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录编号">{{ selectedRecord.recordNo }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ selectedRecord.productName }}</el-descriptions-item>
        <el-descriptions-item label="商品编号">{{ selectedRecord.productCode }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="selectedRecord.recordType === 'IN' ? 'success' : 'warning'">
            {{ selectedRecord.recordTypeName }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="业务类型">
          <el-tag 
            :type="getBusinessTypeTagType(selectedRecord.businessType)"
            effect="plain"
          >
            {{ selectedRecord.businessTypeName }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作数量">{{ selectedRecord.quantity }}</el-descriptions-item>
        <el-descriptions-item label="操作前库存">{{ selectedRecord.beforeStock }}</el-descriptions-item>
        <el-descriptions-item label="操作后库存">{{ selectedRecord.afterStock }}</el-descriptions-item>
        <el-descriptions-item label="单位成本">
          <span v-if="selectedRecord.unitCost">¥{{ selectedRecord.unitCost }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="总成本">
          <span v-if="selectedRecord.totalCost">¥{{ selectedRecord.totalCost }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="操作员">{{ selectedRecord.operatorName }}</el-descriptions-item>
        <el-descriptions-item label="目标商家">
          <span v-if="selectedRecord.targetMerchantName">{{ selectedRecord.targetMerchantName }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间" :span="2">
          {{ formatDateTime(selectedRecord.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          <span v-if="selectedRecord.remark">{{ selectedRecord.remark }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { adminInventoryApi } from '@/api/adminInventory'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const selectedRecord = ref({})

// 搜索表单
const searchForm = reactive({
  productName: '',
  productCode: '',
  recordType: '',
  businessType: '',
  operatorName: '',
  targetMerchantName: '',
  dateRange: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取库存记录
const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      productName: searchForm.productName,
      productCode: searchForm.productCode,
      recordType: searchForm.recordType,
      businessType: searchForm.businessType,
      operatorName: searchForm.operatorName,
      targetMerchantName: searchForm.targetMerchantName,
      startTime: searchForm.dateRange ? searchForm.dateRange[0] : null,
      endTime: searchForm.dateRange ? searchForm.dateRange[1] : null
    }
    const response = await adminInventoryApi.getRecordsPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取库存记录失败')
    }
  } catch (error) {
    console.error('获取库存记录失败:', error)
    ElMessage.error('获取库存记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.productName = ''
  searchForm.productCode = ''
  searchForm.recordType = ''
  searchForm.businessType = ''
  searchForm.operatorName = ''
  searchForm.targetMerchantName = ''
  searchForm.dateRange = null
  pagination.current = 1
  getTableData()
}

// 刷新
const handleRefresh = () => {
  getTableData()
}

// 导出
const handleExport = async () => {
  try {
    const params = {
      productName: searchForm.productName,
      productCode: searchForm.productCode,
      recordType: searchForm.recordType,
      businessType: searchForm.businessType,
      operatorName: searchForm.operatorName,
      targetMerchantName: searchForm.targetMerchantName,
      startTime: searchForm.dateRange ? searchForm.dateRange[0] : null,
      endTime: searchForm.dateRange ? searchForm.dateRange[1] : null
    }
    const response = await adminInventoryApi.exportRecords(params)
    if (response.code === 200) {
      // TODO: 实现文件下载逻辑
      ElMessage.success('导出成功')
    } else {
      ElMessage.error(response.message || '导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 查看详情
const handleViewDetail = (row) => {
  selectedRecord.value = { ...row }
  detailDialogVisible.value = true
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getTableData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getTableData()
}

// 获取业务类型标签类型
const getBusinessTypeTagType = (businessType) => {
  switch (businessType) {
    case 'CREATE':
      return 'success'
    case 'ALLOCATE':
      return 'primary'
    case 'ADJUST':
      return 'warning'
    default:
      return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.admin-inventory-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.search-area .el-form {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
}

.search-area .el-form-item {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}
</style> 